#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "treeMgt.h"

static int level = 1; /* Indentation level */

void simuTab();

TreeNode * newTreeNode( char * label ) {
  /* Allocating memory for node */
  TreeNode *node = malloc(sizeof(TreeNode));
  if (node == NULL) { fprintf(stderr,"Erreur lors de l'allocation memoire"); abort(); }
  /* Copying label to Node */
  node->label = malloc((strlen(label) + 1) * sizeof(char));
  strcpy(node->label,label);

  return node; 
}
Tree  * newTree(TreeNode * tnP ) {
  /* Allocating memory for Tree */
  Tree *tree = malloc(sizeof(Tree));
  if (tree == NULL) { fprintf(stderr,"Erreur lors de l'allocation memoire"); abort(); }
  /* Setting TreeNode */
  tree->node = tnP;
 
  return tree;
}
void addChildToParentNode(TreeNode * parentP, TreeNode * childP ) {
  TreeNode *courantP;
  if (parentP->firstChild == NULL) {
    parentP->firstChild = childP;
  }
  else {
    courantP = parentP->firstChild;
    while (courantP->nextBrother != NULL) {
      courantP=courantP->nextBrother;
    }
    courantP->nextBrother = childP;
  }
}
TreeNode * getNodeFromRoot(Tree *t) {
  return t->node;
}
void dfsTraversalOn(TreeNode * tnP) {
  char *label = malloc((strlen(tnP->label) + 1) * sizeof(char));
  TreeNode *courantP=tnP;

  label = tnP->label;

  simuTab(); fprintf(stderr,"<li> %s\n", label);
  simuTab(); fprintf(stderr,"  <ul>\n");
  if (courantP->firstChild != NULL) {
    courantP = courantP->firstChild;
  }
  while (courantP->nextBrother != NULL) {
      if (courantP->firstChild != NULL) { level ++; simuTab(); dfsTraversalOn(courantP); level--; }
    	else { simuTab(); fprintf(stderr,"    <li>%s</li>\n",courantP->label); }
    	courantP=courantP->nextBrother;
  } 
  simuTab(); fprintf(stderr,"    <li>%s</li>\n",courantP->label); /* UGLY BUT WORKING */


  simuTab(); fprintf(stderr,"  </ul>\n");
  simuTab(); fprintf(stderr,"</li>\n");
}
void simuTab() {
  int i;
  for (i=0; i < level; i++) {
    fprintf(stderr, " ");
  }
}
